package com.magic.gre.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.magic.gre.GREApp;
import com.magic.gre.R;
import com.magic.gre.adapter.OffLineAdapter;
import com.magic.gre.base.activity.BaseMVPActivity;
import com.magic.gre.mvp.contract.OffLineContract;
import com.magic.gre.mvp.presenter.OffLinePresenterImpl;
import com.magic.gre.receiver.NetworkChangeReceiver;
import com.magic.gre.ui.dialog.NetHintDialog;
import com.noname.lib_base_java.entity.MsgEvent;
import com.noname.lib_base_java.global.GlobalApplication;
import com.noname.lib_base_java.net.download.DownloadInfo;
import com.noname.lib_base_java.net.download.DownloadManager;
import com.noname.lib_base_java.net.download.FileUtil;
import com.noname.lib_base_java.util.L;
import com.noname.lib_base_java.util.ToastUtil;

import org.zeroturnaround.zip.ZipUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Author: Lmoumou
 * Date: 2019-01-10 18:28
 * 文件名: OffLineActivity
 * 描述:
 */
public class OffLineActivity extends BaseMVPActivity<OffLinePresenterImpl> implements OffLineContract.View,
        DownloadManager.ProgressListener, OffLineAdapter.OnItemClickListener,NetHintDialog.OnNetHintDialogListener {

    private static final String TAG = "OffLineActivity";
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.net_status_tv)
    TextView netStatusTv;

    public static void startThis(Context context) {
        Intent intent = new Intent(context.getApplicationContext(), OffLineActivity.class);
        context.startActivity(intent);
    }

    private OffLineAdapter adapter;
    private List<DownloadInfo> dataList = new ArrayList<>();
    private DownloadInfo info;
    private NetworkChangeReceiver receiver;
    private int netStatus = 0;
    private NetHintDialog netHintDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_off_line;
    }

    @Override
    protected OffLinePresenterImpl creatPresenter() {
        return new OffLinePresenterImpl(this);
    }

    @Override
    protected void netOverride() {

    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void handlerMsg(MsgEvent msgEvent) {
        super.handlerMsg(msgEvent);
        switch (msgEvent.getEvent()) {
            case MsgEvent.NET_STATUS:
                netStatus = (int) msgEvent.get("status");
                if (netStatus == 1) {
                    netStatusTv.setText("当前为运营商网络");
                } else if (netStatus == 0) {
                    netStatusTv.setText("当前为网络不可用");
                } else {
                    netStatusTv.setText("当前为Wi-Fi网络，切换至运营商流量会自动暂停下载");
                }
                break;
        }
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        registerRxBus();

        mSmartRefreshLayout.setEnableRefresh(false);
        mSmartRefreshLayout.setEnableLoadMore(false);

        //注册广播
        receiver = new NetworkChangeReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(receiver, filter);


        adapter = new OffLineAdapter(this, dataList);
        adapter.setOnItemClickListener(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(adapter);

        initData();

    }

    /**
     * 初始化数据
     */
    private void initData() {
        String path = Environment.getExternalStorageDirectory() + File.separator + GlobalApplication.getContext().getPackageName() + File.separator + "Download" + File.separator + "downloadinfo.txt";
        File file = new File(path);
        if (file.exists()) {
            try {
                String content = FileUtil.readTxtFile(file);
                L.e(TAG, "content->" + content);
                List<DownloadInfo> contentList = new Gson().fromJson(content, new TypeToken<List<DownloadInfo>>() {
                }.getType());
                dataList.addAll(contentList);
                adapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDowanload(DownloadInfo info) {
        this.info = info;
        if (netStatus == 1) {
            if (netHintDialog == null) {
                netHintDialog = new NetHintDialog();
                netHintDialog.setOnNetHintDialogListener(this);
            }
            netHintDialog.showThis(getSupportFragmentManager(),NetHintDialog.class.getSimpleName());
        } else if (netStatus == 0) {
            ToastUtil.getInstance().showNormal(this, "当前网络不可用");
        } else {
            showLoadDialog();
            mPresenter.pDownload(info, this);
        }

    }

    @Override
    public void progressChanged(long read, long contentLength, boolean done) {
        if (done) {
            File file = new File(info.getSavePath());

            if (file.exists()) {

                info.setReadLength(file.length());
                info.setContentLength(file.length());
                adapter.notifyDataSetChanged();
                String sPath = Environment.getExternalStorageDirectory() + File.separator + GREApp.getContext().getPackageName() + File.separator + "Download" + File.separator + info.getThesaurus_id();
                File file2 = new File(sPath);
                if (file2.exists()) {
                    file2.delete();
                }

                ZipUtil.unpack(new File(info.getSavePath()), file2);
            }
            ToastUtil.getInstance().showNormal(this, "下载完成");
            hideLoadDialog();
        }
    }

    @Override
    public void onAreadyDownload(DownloadInfo info) {
        hideLoadDialog();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    @Override
    public void onContinueDowanload() {
        showLoadDialog();
        mPresenter.pDownload(info, this);
    }
}
